package com.weilele.mvvm.utils.clipboard

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import com.weilele.mvvm.app
import com.weilele.mvvm.packageName

val clipboardManager by lazy { app.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager }

/**
 * 获取剪切板的内容
 */
fun Any?.getClipboardContent(): String? {
    val context = if (this is Context) this else app
    val data = clipboardManager.primaryClip
    return if (data != null && data.itemCount > 0) {
        data.getItemAt(0).coerceToText(context).toString()
    } else {
        return null
    }
}

/**
 * 内容赋值到剪切板
 */
fun CharSequence?.copyToClipboard() {
    this ?: return
    clipboardManager.setPrimaryClip(ClipData.newPlainText(packageName, this))
}

/**
 * 清空剪切板
 */
fun clearClipboard() {
    "".copyToClipboard()
}